<template>
  <div class="material-edit-dialog display-flex w-full h-full" style="justify-content: flex-start;overflow: hidden">
    <div class="inv-data-box right-border h-full flex-1" style="overflow: auto">
      <a-tree
        :selectedKeys="invDataSelected"
        ref="invDataTree"
        v-if="invDataTree && invDataTree.length > 0"
        :tree-data="invDataTree"
        :expandedKeys="invDefaultExpandedKeys"
        @expand="(selectedKeys,e) => handlerDataExpend(selectedKeys,e,'invDefaultExpandedKeys')"
        @select="(selectedKeys,e) => handlerDataSelect(selectedKeys,e,'invDataSelected','invMaterialSelected')"
        :replaceFields="{title:'material_name',key:'id'}">
        <template slot="title" slot-scope="record">
          <div :title="record.material_name">{{ `${(record.mate_sort_uuid && (record.mate_sort_uuid !== record.material_name)) ? ('(' + record.mate_sort_uuid + ')') : ''}${record.material_name}` }}</div>
        </template>
      </a-tree>
    </div>
    <div class="biz-data-box right-border h-full flex-1" style="overflow: auto">
      <a-tree
        :selectedKeys="bizDataSelected"
        ref="bizDataTree"
        v-if="dataModelList && dataModelList.length > 0"
        :tree-data="dataModelList"
        :loadData="(node) => loadBizDataModelData(node)"
        :loadedKeys="bizDataModelLoadKeys"
        :expandedKeys="bizDefaultExpandedKeys"
        @expand="(selectedKeys,e) => handlerDataExpend(selectedKeys,e,'bizDefaultExpandedKeys')"
        @select="(selectedKeys,e) => handlerDataSelect(selectedKeys,e,'bizDataSelected','bizMaterialSelected')"
        :replaceFields="{title:'name',key:'id'}">
        <template slot="title" slot-scope="record">
          {{ `${record.name} ` }}
        </template>
      </a-tree>
    </div>
  </div>
</template>
<script>
import businessService from '@/api/businessService'
import dapProjectService from '@/api/dapProjectService'

export default {
  name: 'MaterialEditDialog',
  props: {
    businessType: {
      type: Object,
      default: () => {
        return {}
      }
    },
    category: {
      type: String,
      default: () => {
        return ''
      }
    },
    sourceId: {
      type: Number,
      default: () => {
        return 0
      }
    },
    materialDirectoryName: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      invDataTree: [],
      invDefaultExpandedKeys: [],
      invDataSelected: [],
      invDataSelectedObj: {},
      dataModelList: [],
      bizDataModelLoadKeys: [],
      bizDefaultExpandedKeys: [],
      bizDataSelected: [],
      bizDataSelectedObj: {}
    }
  },
  async mounted () {
    if (this.sourceId) {
      await this.getSourceInfo()
    }
    this.initInvMaterialList()
    this.initBizMaterialList()
  },
  methods: {
    async getSourceInfo () {
      const data = await dapProjectService.getBusinessItemMaterialMapById(this.sourceId)
      localStorage.setItem('invMaterialSelected', JSON.stringify({
        materialName: data.material_name,
        rootId: data.category
      }))
      localStorage.setItem('bizMaterialSelected', JSON.stringify({
        materialName: this.materialDirectoryName,
        rootId: data.materialCategoryId
      }))
    },
    async loadBizDataModelData (node, after) {
      const data = await businessService.getBusinessMaterialDetail(node.dataRef.id)
      const children = data.children || []
      children.forEach(item => {
        item.nodeType = 'directory'
        item.isLeaf = true
        item.categoryName = node.dataRef.name
      })
      node.dataRef.children = children
      this.bizDataModelLoadKeys.push(node.dataRef.id)
      if (after) {
        after(node.dataRef)
      }
    },
    async initInvMaterialList () {
      const data = await businessService.getInvestmentMaterialByItemCodeSource(this.businessType.item_code, this.businessType.source)
      const commonList = []
      const extList = []
      const desList = []
      data.forEach(item => {
        item.nodeType = 'directory'
        if (item.category === 'common') {
          commonList.push(item)
        }
        if (item.category === 'ext') {
          extList.push(item)
        }
        if (item.category === 'des') {
          desList.push(item)
        }
      })
      const treeList = [
        {
          id: 'common',
          material_name: '基本流程材料',
          children: commonList
        },
        {
          id: 'ext',
          material_name: '延期变更材料',
          children: extList
        },
        {
          id: 'des',
          material_name: '注销材料',
          children: desList
        }
      ]
      const dataLogStr = localStorage.getItem('invMaterialSelected')
      if (dataLogStr) {
        const dataLog = JSON.parse(dataLogStr)
        if (dataLog.rootId) {
          const find = this._.find(treeList, item => item.id === dataLog.rootId)
          if (find) {
            const children = find.children
            const findChild = this._.find(children, item => item.material_name === dataLog.materialName)
            if (findChild) {
              this.invDefaultExpandedKeys = [find.id]
              this.invDataSelected = [findChild.id]
              this.invDataSelectedObj = findChild
            }
          }
        }
      }
      this.invDataTree = treeList
    },
    async initBizMaterialList () {
      let businessId = ''
      if (this.category === 'des') {
        businessId = '2c92b0e688b4f91b0188b771bdd50003'
      } else {
        businessId = this.businessType.businessId
      }
      const data = await businessService.getBusinessMaterialById(businessId)
      data.forEach(item => {
        const categoryDTO = item.categoryDTO
        Object.assign(item, categoryDTO)
      })
      const dataLogStr = localStorage.getItem('bizMaterialSelected')
      if (dataLogStr) {
        const dataLog = JSON.parse(dataLogStr)
        const find = this._.find(data, item => item.id === dataLog.rootId)
        if (find) {
          this.loadBizDataModelData({ dataRef: find }, (root) => {
            const children = root.children
            const findChild = this._.find(children, item => item.name === dataLog.materialName)
            if (findChild) {
              this.bizDataSelected = [findChild.id]
              this.bizDataSelectedObj = findChild
              this.bizDefaultExpandedKeys = [find.id]
              this.bizDataModelLoadKeys = [findChild.id]
            }
          })
        }
      }
      this.dataModelList = data
    },
    getSaveData () {
      const result = {
        state: false,
        data: null
      }
      if (!this.invDataSelectedObj.nodeType) {
        this.$message.warning('请选择正确的3.0系统材料')
        return result
      }
      if (!this.bizDataSelectedObj.nodeType) {
        this.$message.warning('请选择正确的业务系统材料')
        return result
      }
      if (this.invDataSelectedObj.category !== this.category) {
        this.$message.warning('流程类型不一致,请重新选择')
        return result
      }
      const params = {
        materialDirectoryId: this.bizDataSelectedObj.id,
        materialCategoryId: this.bizDataSelectedObj.categoryId,
        businessItemMapId: this.businessType.id,
        material_uuid: '',
        item_code: this.businessType.item_code,
        is_required: this.invDataSelectedObj.is_required,
        mate_sort_uuid: this.invDataSelectedObj.mate_sort_uuid,
        material_name: this.invDataSelectedObj.material_name,
        material_type: this.invDataSelectedObj.material_type,
        source: this.invDataSelectedObj.source,
        category: this.invDataSelectedObj.category
      }
      if (this.sourceId) {
        params.id = this.sourceId
      }
      result.state = true
      result.data = params
      return result
    },
    handlerDataExpend (selectedKeys, e, key) {
      this[key] = selectedKeys
    },
    handlerDataSelect (selectedKeys, e, key, logKey) {
      const dataRef = e.node.dataRef
      if (!dataRef.nodeType || dataRef.nodeType !== 'directory') {
        this.$message.warning('当前非变量节点,请正确选择')
        this[key] = []
        this[key + 'Obj'] = {}
        return
      }
      this[key] = selectedKeys
      this[key + 'Obj'] = dataRef
      const selectLog = {
        materialName: dataRef.material_name || dataRef.name,
        rootId: dataRef.category || dataRef.categoryId
      }
      localStorage.setItem(logKey, JSON.stringify(selectLog))
    }
  }
}
</script>

<style scoped lang="less">

</style>
